package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.IDishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 菜品 前端控制器
 * </p>
 *
 * @author fcy
 * @since 2025-09-08
 */
@RestController("adminDishController")
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关接口")
@Slf4j
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 清理缓存
     */
    private void clearCache(String patten){
        Set keys = redisTemplate.keys(patten);
        redisTemplate.delete(keys);
    }
    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result<String> save(@RequestBody DishDTO dishDTO){
        dishService.add(dishDTO);
        String key = "dish_" + dishDTO.getCategoryId();
        clearCache(key);
        return Result.success();
    }
    /**
     * 菜品分页查询
     * @param pageDto
     * @return
     */
    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO  pageDto){
        return dishService.getPage(pageDto);
    }
    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @ApiOperation("修改菜品")
    @PutMapping
    public Result<String> update(@RequestBody DishDTO dishDTO){
        log.info("修改菜品：{}",dishDTO);
        clearCache("dish_*");
        return dishService.change(dishDTO);
    }
    /**
     * 修改菜品回显
     * @param id
     * @return
     */
    @ApiOperation("修改菜品回显")
    @GetMapping("/{id}")
    public Result<DishVO> getById(@PathVariable Long id){
        return dishService.selectById(id);
    }
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<Dish>> list(Integer categoryId){
        return dishService.getList(categoryId);
    }
    /**
     * 起售、停售
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("起售、停售")
    public Result<String> changeStatus(@PathVariable Integer status,Long id){
        dishService.changeStatus(status,id);
        clearCache("dish_*");
        return Result.success();
    }

    @ApiOperation("批量删除菜品")
    @DeleteMapping
    public Result<String> delete(@RequestParam List<Long> ids){
        dishService.delete(ids);
        clearCache("dish_*");
        return Result.success();
    }
}
